<template>
    <el-container>
        <el-header>
            <div class="left-panel">
                <el-button
                    v-if="orgType==1"
                    type="primary"
                    icon="el-icon-plus"
                    @click="opBatchImportJd"
                >批量导出金蝶</el-button>
            </div>
            <div class="right-panel">
                <el-button :icon="Search"   type="primary" @click="opBindData">查询</el-button>
                <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                <el-button text type="primary" @click="showCondition = !showCondition">
                    <span v-if="!showCondition">展开</span>
                    <span v-else>收起</span>
                    <vab-icon
                        class="vab-dropdown"
                        :class="{ 'vab-dropdown-active': fold }"
                        icon="arrow-up-s-line"
                    />
                </el-button>
            </div>
        </el-header>
        <el-foot v-show="showCondition">
            <vab-query-form-top-panel>
                <el-form inline label-width="49px" :model="queryForm" style="margin-top: 5px">
                    <el-form-item label="对账日期" label-width="100px">
                        <el-date-picker
                            style="width: 300px"
                            v-model="queryList.accountDate"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            range-separator="-"
                            unlink-panels="true"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :default-time="defaultTime"
                        />
                    </el-form-item>
                    <el-form-item label="对账申请编号" label-width="100px">
                        <el-input
                            placeholder="---请输入对账申请编号---"
                            v-model="queryList.accountCode"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="对账申请日期" label-width="100px">
                        <el-date-picker
                            style="width: 300px"
                            v-model="queryList.accountTime"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            range-separator="-"
                            unlink-panels="true"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :default-time="defaultTime"
                        />
                        <!-- <el-input placeholder="---请输入对账申请日期---" v-model="queryList.accountTime" style="width: 300px" /> -->
                    </el-form-item>
                    <el-form-item label="申请人" label-width="100px">
                        <el-input
                            placeholder="---请输入申请人---"
                            v-model="queryList.applicantUser"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="联系电话" label-width="100px">
                        <el-input
                            placeholder="---请输入联系电话---"
                            v-model="queryList.tel"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="对账状态" label-width="100px">
                        <el-select
                            placeholder="---请选择状态---"
                            v-model="queryList.reconciliationStatus"
                            style="width: 300px"
                        >
                            <el-option label="---请选择状态---" value />
                            <el-option
                                v-for="item in optionsState"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="客户" label-width="100px">
                        <el-input
                            placeholder="---请输入客户名称---"
                            v-model="queryList.storeName"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="物料简码" label-width="100px">
                        <el-input
                            placeholder="---请输入物料简码---"
                            v-model="queryList.materialSimpCode"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="物料编号" label-width="100px">
                        <el-input
                            placeholder="---请输入物料编号---"
                            v-model="queryList.materialCode"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="物料分类" label-width="100px">
                        <el-tree-select
                            v-model="queryList.materialTypeIds"
                            placeholder="---请选择物料分类---"
                            :props="{ label: 'label', value:'value',children: 'children' }"
                            :data="materialTypeTree"
                            multiple
                            :render-after-expand="false"
                            show-checkbox
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="物料名称" label-width="100px">
                        <el-input
                            placeholder="---请输入物料名称---"
                            v-model="queryList.materialName"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="规格型号" label-width="100px">
                        <el-input
                            placeholder="---请输入规格型号---"
                            v-model="queryList.materialSpecs"
                            style="width: 300px"
                        />
                    </el-form-item>
                </el-form>
            </vab-query-form-top-panel>
        </el-foot>

        <el-main class="nopadding">
            <scTable
                ref="mytable"
                border
                :queryType="'sales-account/pages'"
                :data="listData"
                :queryList="queryList"
                :column="columnList"
                :orderList="OrderList"
                :sort-orders="['ascending', 'descending']"
                @selection-change="selectionChange"
                row-key="ReceivingOrderId"
                key="ReceivingOrderId"
                stripe
                show-summary
                remoteSummary
            >
                <el-table-column type="selection" width="50"></el-table-column> 
                <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
                <el-table-column label="对账日期" width="200">
                    <template #default="scope">
                        {{scope.row.accountStartDate.length>10? scope.row.accountStartDate.slice(0, 10):scope.row.accountStartDate}}
                        {{'-'}}
                        {{scope.row.accountEndDate.length>10? scope.row.accountEndDate.slice(0, 10):scope.row.accountEndDate}}
                    </template>
                </el-table-column>

                <el-table-column label="对账状态" prop="reconciliationStatus" min-width="100">
                    <template #default="scope">
                        {{scope.row.reconciliationStatus==0?'已关账':''}}
                        {{scope.row.reconciliationStatus==1?'已对账':''}}
                        {{scope.row.reconciliationStatus==2?'已发送申请':''}}
                        {{scope.row.reconciliationStatus==3?'对账中':''}}
                    </template>
                </el-table-column>

                <el-table-column label="对账申请单位" prop="purchaseUnityFullName" width="250"></el-table-column>
                <el-table-column label="申请人" prop="applicantUser" min-width="90"></el-table-column>
                <el-table-column label="联系电话" prop="tel" min-width="150"></el-table-column>
                <el-table-column label="客户" prop="storeName" min-width="140"></el-table-column>
                <el-table-column label="对账明细表" prop="materialCode" width="150">
                    <template #default="scope">
                        <el-button-group>
                            <el-button
                                text
                                type="primary"
                                size="small"
                                @click="opHandleView(scope.row, '3')"
                            >查看</el-button>
                            <el-button
                                text
                                type="primary"
                                size="small"
                                @click="opExport(scope.row)"
                            >下载</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
                <el-table-column label="相关附件" prop="materialName" width="150">
                    <template #default="scope">
                        <el-button-group>
                            <el-button
                                v-if="scope.row.accountFile!=''"
                                text
                                type="primary"
                                size="small"
                                @click="opOfficePreview(scope.row, scope.$index)"
                            >查看</el-button>
                            <el-button
                                text
                                type="primary"
                                size="small"
                                @click="opDownFile(scope.row, scope.$index)"
                            >下载</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
                <el-table-column label="对账申请日期" prop="accountTime" min-width="200"></el-table-column>

                <el-table-column label="对账申请编号" prop="accountCode" width="200">
                    <template #default="scope">
                        <span
                            class="el-span-text"
                            @click="opHandleView(scope.row, scope.$index)"
                        >{{scope.row.accountCode}}</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" fixed="right" width="230" align="center">
                    <template #default="scope">
                        <el-button-group>
                            <el-button
                                v-if="scope.row.reconciliationStatus!=1"
                                text
                                type="primary"
                                size="small"
                                @click="opEnd(scope.row, '2')"
                            >结束对账</el-button>
                            <el-button
                                v-if="scope.row.reconciliationStatus!=1"
                                text
                                type="primary"
                                size="small"
                                @click="opHandleView(scope.row, '1')"
                            >进行对账</el-button>
                            <el-button
                                text
                                type="warning"
                                size="small"
                                v-if="orgType==1 && scope.row.reconciliationStatus==1 && !scope.row.isImportJd"
                                @click="opAntiAudit(scope.row, scope.$index)"
                            >反 审 核&nbsp;</el-button>
                            <el-button
                                v-if="scope.row.reconciliationStatus!=1"
                                text
                                type="primary"
                                size="small"
                                @click="openDel(scope.row)"
                            >删除</el-button>
                            <el-button
                                v-if="scope.row.reconciliationStatus==1"
                                text
                                type="primary"
                                size="small"
                                @click="opImportJd([scope.row.salesAccountID])"
                            >金蝶导出</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
                <el-table-column
                    label="应收账款"
                    prop="name"
                    fixed="right"
                    width="150"
                    align="center"
                    v-if="orgType==1"
                >
                    <template #default="scope">
                        <el-button-group>
                            <el-button
                                text
                                type="success"
                                size="small"
                                @click="createBill(scope.row, scope.$index)"
                                v-if="scope.row.reconciliationStatus==1 && scope.row.isCreateBill==0"
                            >生成</el-button>
                            <el-button text type="success" size="small" v-else>---</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </scTable>

              <!--对账信息的：查看3 编辑2 申请1 -->
    <reconciliation-doing
        v-if="dialogCheck"
        ref="checkDialog"
        @fatherMethod="opBindData"
        @success="handleSaveSuccess"
        @closed="closed"
    ></reconciliation-doing>
        </el-main>
        
    </el-container>

  

    <!-- 预览文件 -->
    <officeViewer ref="officeDialog" />
</template>

<script>
import publicjs from "@/api/model/publicjs";
import tool from "@/utils/tool";
import reconciliationDoing from "./reconciliationDoing";
export default {
    components: {
        publicjs,
        reconciliationDoing,
    },
    data() {
        return {
            orgType: "",
            columnList: [],
            queryList: {},
            selectionRows: [],
            showCondition: false,
            dialogCheck: false,
            materialTypeTree: [],
            optionsState: [
                {
                    value: 1,
                    label: "已对账",
                },
                {
                    value: 2,
                    label: "未对账",
                },
                {
                    value: 3,
                    label: "对账中",
                },
                {
                    value: 4,
                    label: "已发送申请",
                },
            ],
            defaultTime: [
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ],
        };
    },
    methods: {
        opOfficePreview(row) {
            // 预览操作，打开对话框显示图片
            this.$refs.officeDialog.setData(row.accountFile);
            this.$refs.officeDialog.open();
        },
        // 3 仅查看  2.编辑申请  1.进行对账
        opHandleView(row, type) {
            this.dialogCheck = true;
            if (type == "1") {
                this.opStartAccount(row);
            }
            this.$nextTick(() => {
                this.$refs.checkDialog.initTable(row, type);
            });
        },
        async opEnd(row) {
            try {
                var response = await this.$API.auth.PostProcessApi.post(
                    "sales-account/isAllCheck",
                    row
                );
                console.log(response);
                debugger;
                if (response.status == 200) {
                    this.$confirm(response.msg + ",是否继续?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }).then(async () => {
                        var endresponse =
                            await this.$API.auth.PostProcessApi.post(
                                "sales-account/endAccount",
                                row
                            );
                        if (endresponse.status == 200) {
                            this.$message.success("结束账单成功");
                            this.opBindData();
                        } else {
                            this.$message.error(endresponse.msg);
                        }
                    });
                } else {
                    this.$message.error(response.msg);
                }
            } catch (error) {
                this.loading = false;
                this.$message.error(error.msg);
                return false;
            }
        },
        async opBindData() {
            this.$refs.mytable.clearSort();
            this.$refs.mytable.getData();
        },
        //开始对账
        async opStartAccount(row) {
            try {
                var response = await this.$API.auth.PostDownApi.post(
                    "sales-account/startaccount",
                    {
                        salesAccountID: row.salesAccountID,
                    }
                );
                if (response.status == 200) {
                    this.opBindData();
                } else {
                    this.$message.error("操作失败:" + response.msg);
                }
            } catch (error) {
                this.loading = false;
                this.$message.error(error.message);
                return false;
            }
        },
        resetSearch() {
            this.queryList = {};
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
            console.log(this.selectionRows);
        },
        async opExport(row) {
            try {
                var response = await this.$API.auth.PostDownApi.post(
                    "sales-account/export",
                    {
                        salesAccountID: row.salesAccountID,
                        accountStartDate: row.accountStartDate,
                        accountEndDate: row.accountEndDate,
                    }
                );

                var beginDate = row.accountStartDate.substring(0, 10);
                var endDate = row.accountEndDate.substring(0, 10);
                // 获取 Content-Disposition 头部信息
                debugger;
                const headers = new Headers(response.headers);
                console.log(headers);
                let fileName = headers.get("File-Name");
                console.log(fileName);
                fileName = decodeURIComponent(fileName);
                console.log(fileName);
                if (!fileName || fileName == "null") {
                    fileName =
                        "对账明细(" + beginDate + "至" + endDate + ").xlsx";
                }
                console.log(fileName);
                const blob = new Blob([response.data], {
                    type: "application/xlsx",
                });
                // 创建一个临时的 URL 对象，指向下载的 Blob 数据
                const url = window.URL.createObjectURL(blob);
                // 创建一个 <a> 元素，设置其 href 属性为 URL，并触发点击
                const a = document.createElement("a");
                a.href = url;
                a.download = fileName; // 下载时显示的文件名为从头信息中获取的文件名
                document.body.appendChild(a); // 将 <a> 元素添加到 DOM 中
                a.click(); // 模拟点击下载
                document.body.removeChild(a); // 下载完成后移除 <a> 元素
                window.URL.revokeObjectURL(url); // 释放 Blob 对象
            } catch (error) {
                this.loading = false;
                this.$message.error(error.message);
                // this.$alert(error.message, "提示", {
                // 	type: "error"
                // });
                return false;
            }
        },
        opDownFile(row) {
            debugger;
            if (row.accountFile == null || row.accountFile.length <= 0) {
                this.$message.error("暂无附件");
            } else {
                const url = new URL(row.accountFile);
                const fileName = url.pathname.split("/").pop(); // 获取文件名
                fetch(row.accountFile)
                    .then((response) => response.blob())
                    .then((blob) => {
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement("a");
                        a.style.display = "none";
                        a.href = url;
                        a.download = fileName;
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                    })
                    .catch((error) => console.error("下载失败:", error));
            }
        },
        //金蝶批量导出
        async opBatchImportJd() {
            if (this.selectionRows.length == 0) {
                this.$message.error("请选择要导出的单据");
                return;
            }
           const salesAccountIds= this.selectionRows.map((row) =>row.salesAccountID);
           await this.opImportJd(salesAccountIds);
        },
        //金蝶导出
        async opImportJd(salesAccountIds) {
            try {
                var response = await this.$API.auth.PostProcessApi.post(
                    `sales-account/import-jd-detail`,
                    {salesAccountIds:salesAccountIds}
                );
                if (response.status == 200) {
                    if (
                        response.response.saleReceivingOrderIds &&
                        response.response.saleReceivingOrderIds.length > 0
                    ) {
                        await this.$API.auth.PostDownApi.post(
                            "receiving-order/down-jd-file",
                            {
                                receivingOrderIds:response.response.saleReceivingOrderIds,
                            }
                        )
                            .then((res) => {
                                this.downloadfile(res.data);
                            })
                            .catch((err) => {
                                this.$message.error("下载错误：获取文件流错误");
                            });
                    }

                    if (
                        response.response.afterReceivingOrderIds &&
                        response.response.afterReceivingOrderIds.length > 0
                    ) {
                        await this.$API.auth.PostDownApi.post(
                            "receiving-order/down-jdtk-file",
                            {
                                receivingOrderIds:response.response.afterReceivingOrderIds,
                            }
                        )
                            .then((res) => {
                                this.downloadfile(res.data);
                            })
                            .catch((err) => {
                                this.$message.error("下载错误：获取文件流错误");
                            });
                    }
                } else {
                    this.$message.error("操作失败:" + response.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
		downloadfile(blob) {
            console.log("res", blob);
            let fileReader = new FileReader();
            //var blob = new Blob([res], {type: 'application/octet-stream;charset=UTF-8'})
            fileReader.onload = function () {
                try {
                    var downloadElement = document.createElement("a");
                    var href = window.URL.createObjectURL(blob); // 创建下载的链接
                    downloadElement.style.display = "none";
                    downloadElement.href = href;
                    downloadElement.download = decodeURI("明细.xlsx"); // 下载后文件名
                    document.body.appendChild(downloadElement);
                    downloadElement.click(); // 点击下载
                    document.body.removeChild(downloadElement); // 下载完成移除元素
                    window.URL.revokeObjectURL(href);
                } catch (err) {
                    console.log(err);
                }
            };
            fileReader.readAsText(blob);
        },
        //开始对账
        async opStartAccount(row) {
            try {
                var response = await this.$API.auth.PostDownApi.post(
                    "sales-account/startaccount",
                    {
                        salesAccountID: row.salesAccountID,
                    }
                );
                if (response.status == 200) {
                    this.opBindData();
                } else {
                    this.$message.error("操作失败:" + response.msg);
                }
            } catch (error) {
                this.loading = false;
                this.$message.error(error.message);
                return false;
            }
        },
        //生成应收账单
        async createBill(row) {
            console.log("生成账单", row);
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "sales-account/createBill",
                    {
                        SalesAccountId: row.salesAccountID,
                    }
                );
                if (returnValue.status == 200) {
                    this.$message.success("操作成功");
                    await this.opBindData();
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    {
                        status: 1,
                    }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        //反审核
        opAntiAudit(row) {
            this.$confirm("是否反审核?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    try {
                        var response = await this.$API.auth.PostDownApi.post(
                            "sales-account/anti-audit",
                            {
                                salesAccountID: row.salesAccountID,
                            }
                        );
                        if (response.status == 200) {
                            this.opBindData();
                        } else {    
                            this.$message.error("操作失败:" + response.msg);
                        }
                    } catch (error) {
                        this.loading = false;
                        this.$message.error(error.message);
                        return false;
                    }
                })
                .catch(() => {});
                // 用户点击了取消按钮，不执行关闭
        },
        //删除
        async openDel(row) {
            this.$confirm("删除后无法恢复,确认要删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    try {
                        var response = await this.$API.auth.PostDownApi.post(
                            "sales-account/del-sale-account",
                            {
                                salesAccountID: row.salesAccountID,
                            }
                        );
                        if (response.status == 200) {
                            this.opBindData();
                        } else {
                            this.$message.error("操作失败:" + response.msg);
                        }
                    } catch (error) {
                        this.loading = false;
                        this.$message.error(error.message);
                        return false;
                    }
                })
                .catch(() => {
                    // 用户点击了取消按钮，不执行关闭
                });
        },
        closed() {
            this.dialogCheck = false;
            this.$nextTick(() => {
                this.$refs.mytable.reload();
            });
        },
        handleSaveSuccess() {
            this.$nextTick(() => {
                this.$refs.mytable.reload();
                // this.$refs.mytable.clearSort();
                // this.$refs.mytable.getData();
            });
        },
    },
    async mounted() {
        this.orgType = tool.data.get("USER_INFO").AccountType;
        await this.opBindData();
        await this.initOptions();
    },
};
</script>

<style>
</style>
